<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    protected $table = 'rooms';
    
    protected $fillable = [
        'room_code', 'creator_id', 'status', 'name', 
        'start_time', 'end_time'
    ];
    
    public $timestamps = false;
    
    protected $primaryKey = 'id';
    
    // 房间状态常量
    const STATUS_ACTIVE = 1;
    const STATUS_CLOSED = 2;
    
    /**
     * 生成唯一的房间码
     */
    public static function generateRoomCode()
    {
        do {
            $code = strtoupper(substr(md5(time() . mt_rand()), 0, 6));
        } while (self::where('room_code', $code)->exists());
        
        return $code;
    }
    
    /**
     * 关闭房间
     */
    public function closeRoom()
    {
        $this->status = self::STATUS_CLOSED;
        $this->end_time = time();
        $this->save();
    }
    
    /**
     * 获取房间内的所有用户
     */
    public function getUsers()
    {
        return RoomUser::where('room_id', $this->id)->get();
    }
}